/*
 * @Date: 2020-08-07 16:12:28
 * @LastEditors: xujianxing
 * @LastEditTime: 2020-08-07 17:59:35
 * @FilePath: \my-umi\src\models\counter.ts
 */

import { Effect, Reducer, Subscription } from 'umi';
import { getRecommend } from '@/services';
export interface IndexModelState {
  count: number;
}
export interface IndexModelType {
  namespace: 'counter';
  state: IndexModelState;
  effects: {
    query?: Effect;
  };
  reducers: {
    add?: Reducer<IndexModelState>;
    cut?: Reducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'counter',
  state: {
    count: 0,
  },
  /**
   * 所有异步操作
   */
  effects: {
    /**
     * put: 触发action流动到reducer中处理
     * call: 触发其他 effects 或者 返回 Promise 的请求
     * select: 可拿到 state 中的数据
     */
    *query({ payload }, { put, call, select }) {
      const { count } = select((state: any) => state.counter);
      const data = yield call(getRecommend);
      yield put({ type: 'add', payload });
    },
  },
  /**
   * 传统 reducer 触发state的更新
   */
  reducers: {
    add(state, action) {
      return {
        ...state,
        count: state?.count + action.payload || 0,
      };
    },
    cut(state, action) {
      const data = action.payload;
      return {
        ...state,
        count: state?.count - data,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {},
  },
};
export default IndexModel;
